package com.yalpuz.wechat;

import com.yalpuz.wechat.util.WeChatUtils;
import org.json.JSONObject;
import org.json.XML;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.ServletContextAware;

import javax.annotation.PostConstruct;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

@Controller
@RequestMapping("/wechat")
public class WeChatController implements ServletContextAware {
	Logger logger = Logger.getLogger(WeChatController.class.getName());

	private ServletContext servletContext;

	@PostConstruct
	private void postConstruct() throws IOException {
		FileHandler fileHandler = new FileHandler(servletContext.getRealPath("") + "/WeChat.log", true);
		fileHandler.setEncoding("utf-8");
		fileHandler.setFormatter(new SimpleFormatter());
		logger.addHandler(fileHandler);
	}

	/**
	 * 验证消息的确来自微信服务器
	 *
	 * @param signature
	 * @param timestamp
	 * @param nonce
	 * @param echostr
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET, params = {"signature", "timestamp", "nonce", "echostr"})
	@ResponseBody
	public Object wechat(String signature, String timestamp, String nonce, String echostr) {
		String signature2 = WeChatUtils.sha1("Token", timestamp, nonce);
		logger.info(signature);
		logger.info(timestamp);
		logger.info(nonce);
		logger.info(echostr);
		logger.info(signature2);
		if (signature.equals(signature2))
			return echostr;
		return "参数错误";
	}

	@RequestMapping(value = "/json")
	@ResponseBody
	public Object json() {
		Map<Object, Object> json = new HashMap<>();
		json.put("success", true);
		json.put("message", "成功");
		return json;

	}

	@RequestMapping(method = RequestMethod.POST)
	@ResponseBody
	public Object action(@RequestBody String body, HttpServletRequest request) {
		JSONObject xml = XML.toJSONObject(body).getJSONObject("xml");
		logger.info(xml.toString(4));
		return "success";
	}

	/**
	 * 认证JS接口
	 *
	 * @return
	 */
	@RequestMapping("/js/MP_verify_{content}.txt")
	@ResponseBody
	public Object mp(@PathVariable String content) {
		return content;
	}


	@Override
	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}
}
